{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "# GPUs\n",
    ":label:`sec_use_gpu`\n",
    "\n",
    "In the introduction, we discussed the rapid growth\n",
    "of computation over the past two decades.\n",
    "In a nutshell, GPU performance has increased\n",
    "by a factor of 1000 every decade since 2000.\n",
    "This offers great opportunity but it also suggests\n",
    "a significant need to provide such performance.\n",
    "\n",
    "|Decade|Dataset|Memory|Floating Point Calculations per Second|\n",
    "|:--|:-|:-|:-|\n",
    "|1970|100 (Iris)|1 KB|100 KF (Intel 8080)|\n",
    "|1980|1 K (House prices in Boston)|100 KB|1 MF (Intel 80186)|\n",
    "|1990|10 K (optical character recognition)|10 MB|10 MF (Intel 80486)|\n",
    "|2000|10 M (web pages)|100 MB|1 GF (Intel Core)|\n",
    "|2010|10 G (advertising)|1 GB|1 TF (NVIDIA C2050)|\n",
    "|2020|1 T (social network)|100 GB|1 PF (NVIDIA DGX-2)|\n",
    "\n",
    "In this section, we begin to discuss how to harness\n",
    "this compute performance for your research.\n",
    "First by using single GPUs and at a later point,\n",
    "how to use multiple GPUs and multiple servers (with multiple GPUs).\n",
    "\n",
    "In this section, we will discuss how\n",
    "to use a single NVIDIA GPU for calculations.\n",
    "First, make sure you have at least one NVIDIA GPU installed.\n",
    "Then, [download CUDA](https://developer.nvidia.com/cuda-downloads)\n",
    "and follow the prompts to set the appropriate path.\n",
    "Once these preparations are complete,\n",
    "the `nvidia-smi` command can be used\n",
    "to view the graphics card information.\n",
    "\n",
    "You can call external terminal commands from inside the Java kernal by prefixing\n",
    "`%system` to your command.\n",
    "\n",
    "We do this below to call `nvidia-smi` from inside our notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 1,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "%system nvidia-smi"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 2,
    "tab": [
     "mxnet"
    ]
   },
   "source": [
    "You might have noticed that DJL tensor\n",
    "looks almost identical to NumPy.\n",
    "\n",
    "But there are a few crucial differences.\n",
    "One of the key features that distinguishes DJL\n",
    "from NumPy is its support for diverse hardware devices.\n",
    "\n",
    "In DJL, every array has an associated `Device`.\n",
    "So far, by default, all variables\n",
    "and associated computation\n",
    "have been assigned to the CPU.\n",
    "Typically, other contexts might be various GPUs.\n",
    "Things can get even hairier when\n",
    "we deploy jobs across multiple servers.\n",
    "By assigning arrays to `Devices` intelligently,\n",
    "we can minimize the time spent\n",
    "transferring data between devices.\n",
    "For example, when training neural networks on a server with a GPU,\n",
    "we typically prefer for the model's parameters to live on the GPU.\n",
    "\n",
    "To run the programs in this section,\n",
    "you need at least two GPUs.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 4
   },
   "source": [
    "Note that this might be extravagant for most desktop computers\n",
    "but it is easily available in the cloud, e.g.,\n",
    "by using the AWS EC2 multi-GPU instances.\n",
    "Almost all other sections do *not* require multiple GPUs.\n",
    "Instead, this is simply to illustrate\n",
    "how data flows between different devices.\n",
    "\n",
    "## Computing Devices\n",
    "\n",
    "We can specify devices, such as CPUs and GPUs,\n",
    "for storage and calculation.\n",
    "By default, tensors are created in the main memory\n",
    "and then uses the CPU to calculate it.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 5,
    "tab": [
     "mxnet"
    ]
   },
   "source": [
    "In DJL, the CPU and GPU can be indicated by `cpu()` and `gpu()`.\n",
    "It should be noted that `cpu()`\n",
    "(or any integer in the parentheses)\n",
    "means all physical CPUs and memory.\n",
    "This means that DJL's calculations\n",
    "will try to use all CPU cores.\n",
    "However, `gpu()` only represents one card\n",
    "and the corresponding memory.\n",
    "If there are multiple GPUs, we use `gpu(i)`\n",
    "to represent the $i^\\mathrm{th}$ GPU ($i$ starts from 0).\n",
    "Also, `gpu(0)` and `gpu()` are equivalent.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 7,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "%load ../utils/djl-imports"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "System.out.println(Device.cpu());\n",
    "System.out.println(Device.gpu());\n",
    "System.out.println(Device.gpu(1));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 10
   },
   "source": [
    "We can query the number of available GPUs.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 11,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "System.out.println(\"GPU count: \" + Engine.getInstance().getGpuCount());\n",
    "Device d = Device.gpu(1);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 14
   },
   "source": [
    "Now we define two convenient functions that allow us\n",
    "to run codes even if the requested GPUs do not exist.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 15,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "/* Return the i'th GPU if it exists, otherwise return the CPU */\n",
    "public Device tryGpu(int i) {\n",
    "    return Engine.getInstance().getGpuCount() > i ? Device.gpu(i) : Device.cpu();\n",
    "}\n",
    "\n",
    "/* Return all available GPUs or the [CPU] if no GPU exists */\n",
    "public Device[] tryAllGpus() {\n",
    "    int gpuCount = Engine.getInstance().getGpuCount();\n",
    "    if (gpuCount > 0) {\n",
    "        Device[] devices = new Device[gpuCount];\n",
    "        for (int i = 0; i < gpuCount; i++) {\n",
    "            devices[i] = Device.gpu(i);\n",
    "        }\n",
    "        return devices;\n",
    "    }\n",
    "    return new Device[]{Device.cpu()};\n",
    "}\n",
    "\n",
    "System.out.println(tryGpu(0));\n",
    "System.out.println(tryGpu(3));\n",
    "\n",
    "Arrays.toString(tryAllGpus())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 18
   },
   "source": [
    "## Tensors and GPUs\n",
    "\n",
    "By default, tensors are created on the CPU.\n",
    "We can query the device where the tensor is located.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 19,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "NDManager manager = NDManager.newBaseManager();\n",
    "NDArray x = manager.create(new int[]{1, 2, 3});\n",
    "x.getDevice();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 22
   },
   "source": [
    "It is important to note that whenever we want\n",
    "to operate on multiple terms,\n",
    "they need to be in the same context.\n",
    "For instance, if we sum two tensors,\n",
    "we need to make sure that both arguments\n",
    "live on the same device---otherwise the framework\n",
    "would not know where to store the result\n",
    "or even how to decide where to perform the computation.\n",
    "\n",
    "### Storage on the GPU\n",
    "\n",
    "There are several ways to store a tensor on the GPU.\n",
    "For example, we can specify a storage device when creating a tensor.\n",
    "Next, we create the tensor variable `x` on the first `gpu`.\n",
    "Notice that when printing `x`, the device information changed.\n",
    "The tensor created on a GPU only consumes the memory of this GPU.\n",
    "We can use the `nvidia-smi` command to view GPU memory usage.\n",
    "In general, we need to make sure we do not\n",
    "create data that exceeds the GPU memory limit.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 23,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "NDArray x = manager.ones(new Shape(2, 3), DataType.FLOAT32, tryGpu(0));\n",
    "x"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 26
   },
   "source": [
    "Assuming you have at least two GPUs, the following code will create a random array on the second GPU.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 27,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "NDArray y = manager.randomUniform(-1, 1, new Shape(2, 3), DataType.FLOAT32, tryGpu(1));\n",
    "y"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 30
   },
   "source": [
    "### Copying\n",
    "\n",
    "If we want to compute $\\mathbf{x} + \\mathbf{y}$,\n",
    "we need to decide where to perform this operation.\n",
    "For instance, as shown in :numref:`fig_copyto`,\n",
    "we can transfer $\\mathbf{x}$ to the second GPU\n",
    "and perform the operation there.\n",
    "*Do not* simply add `x + y`,\n",
    "since this will result in an exception.\n",
    "The runtime engine would not know what to do,\n",
    "it cannot find data on the same device and it fails.\n",
    "\n",
    "![Copyto copies arrays to the target device](https://raw.githubusercontent.com/d2l-ai/d2l-en/master/img/copyto.svg)\n",
    ":label:`fig_copyto`\n",
    "\n",
    "`copyto` copies the data to another device such that we can add them.\n",
    "Since $\\mathbf{y}$ lives on the second GPU,\n",
    "we need to move $\\mathbf{x}$ there before we can add the two.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 31,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "NDArray z = x.toDevice(tryGpu(1), true);\n",
    "System.out.println(x);\n",
    "System.out.println(z);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 34
   },
   "source": [
    "Now that the data is on the same GPU\n",
    "(both $\\mathbf{z}$ and $\\mathbf{y}$ are),\n",
    "we can add them up.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "origin_pos": 35,
    "tab": [
     "mxnet"
    ]
   },
   "outputs": [],
   "source": [
    "y.add(z)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 36,
    "tab": [
     "mxnet"
    ]
   },
   "source": [
    "Imagine that your variable `z` already lives on your second GPU.\n",
    "What happens if we call still `z.copyto(gpu(1))`?\n",
    "It will make a copy and allocate new memory,\n",
    "even though that variable already lives on the desired device!\n",
    "Just something to remember when you're manually moving data across GPUs."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 41
   },
   "source": [
    "### Side Notes\n",
    "\n",
    "People use GPUs to do machine learning\n",
    "because they expect them to be fast.\n",
    "But transferring variables between contexts is slow.\n",
    "So we want you to be 100% certain\n",
    "that you want to do something slow before we let you do it.\n",
    "If the framework just did the copy automatically\n",
    "without crashing then you might not realize\n",
    "that you had written some slow code.\n",
    "\n",
    "Also, transferring data between devices (CPU, GPUs, other machines)\n",
    "is something that is *much slower* than computation.\n",
    "It also makes parallelization a lot more difficult,\n",
    "since we have to wait for data to be sent (or rather to be received)\n",
    "before we can proceed with more operations.\n",
    "This is why copy operations should be taken with great care.\n",
    "As a rule of thumb, many small operations\n",
    "are much worse than one big operation.\n",
    "Moreover, several operations at a time\n",
    "are much better than many single operations interspersed in the code\n",
    "(unless you know what you are doing)\n",
    "This is the case since such operations can block if one device\n",
    "has to wait for the other before it can do something else.\n",
    "It is a bit like ordering your coffee in a queue\n",
    "rather than pre-ordering it by phone\n",
    "and finding out that it is ready when you are.\n",
    "\n",
    "Last, when we print tensors or convert tensors to the NumPy format,\n",
    "if the data is not in main memory,\n",
    "the framework will copy it to the main memory first,\n",
    "resulting in additional transmission overhead.\n",
    "Even worse, it is now subject to the dreaded Global Interpreter Lock\n",
    "that makes everything wait for Python to complete.\n",
    "\n",
    "\n",
    "## Neural Networks and GPUs\n",
    "\n",
    "Now you may be thinking, well since we have to declare which device we want\n",
    "create NDArrays on, we probably have to declare which device to create our neural\n",
    "network on as well correct?\n",
    "\n",
    "If so, good thinking! DJL, however, actually handles that all for you with `ParameterStore`. \n",
    "So you can train on multiple GPUs and not have to worry about moving data around.\n",
    "Just simply declare and initialize your `Block`s as shown in previous sections and you're good to go!\n",
    "You, however, always have the option of moving data around manually if you like."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 51
   },
   "source": [
    "In short, as long as all data and parameters are on the same device, we can learn models efficiently. In the following we will see several such examples.\n",
    "\n",
    "## Summary\n",
    "\n",
    "* We can specify devices for storage and calculation, such as CPU or GPU.\n",
    "  By default, data are created in the main memory\n",
    "  and then uses the CPU for calculations.\n",
    "* The framework requires all input data for calculation\n",
    "  to be *on the same device*,\n",
    "  be it CPU or the same GPU.\n",
    "* You can lose significant performance by moving data without care.\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Try a larger computation task, such as the multiplication of large matrices,\n",
    "   and see the difference in speed between the CPU and GPU.\n",
    "   What about a task with a small amount of calculations?\n",
    "1. How should we read and write model parameters on the GPU?\n",
    "1. Measure the time it takes to compute 1000\n",
    "   matrix-matrix multiplications of $100 \\times 100$ matrices\n",
    "   and log the matrix norm $\\mathrm{tr} M M^\\top$ one result at a time\n",
    "   vs. keeping a log on the GPU and transferring only the final result.\n",
    "1. Measure how much time it takes to perform two matrix-matrix multiplications\n",
    "   on two GPUs at the same time vs. in sequence\n",
    "   on one GPU (hint: you should see almost linear scaling).\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Java",
   "language": "java",
   "name": "java"
  },
  "language_info": {
   "codemirror_mode": "java",
   "file_extension": ".jshell",
   "mimetype": "text/x-java-source",
   "name": "Java",
   "pygments_lexer": "java",
   "version": "14.0.2+12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
